import { Label } from "@/components/ui/label/label";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { ColumnDef, createColumnHelper } from "@tanstack/react-table";
import { ReactNode } from "react";
import { toast } from "sonner";

const columnHelper = createColumnHelper<GenerateRowProps>();

const defineClassName = {
  color: [
    "bg-purple-400",
    "bg-pink-400",
    "bg-yellow-400",
    "bg-green-400",
    "bg-blue-400",
    "bg-indigo-400",
    "bg-red-400",
  ],
};

const createBgColor = (line?: number, offset?: number) => {
  const getColor = (i: number, _offset?: number) => {
    let index = i % defineClassName.color.length;
    if (_offset) {
      index = (index + _offset) % defineClassName.color.length;
    }
    return defineClassName.color[index];
  };

  if (!line) {
    // 生成 0 到 length - 1 的范围随机数
    line = Math.floor(Math.random() * defineClassName.color.length);
    return getColor(line, offset);
  }
  return getColor(line, offset);
};

const cellContainer = ({
  className,
  children,
}: {
  className?: string;
  children?: ReactNode;
}) => (
  <div className={cn("flex h-full w-full overflow-hidden", className)}>
    {children}
  </div>
);

const columns = [
  columnHelper.accessor("ID", {
    header: "ID",
    cell: (info) =>
      cellContainer({
        className: "mx-2 w-auto items-center-safe",
        children: <Label>{info.getValue()}</Label>,
      }),
  }),
  columnHelper.accessor("NodeType", {
    header: () =>
      cellContainer({
        className: "w-full items-center justify-center",
        children: "笔记类型",
      }),
    cell: (info) =>
      cellContainer({
        className: "items-center justify-center",
        children: (
          <Label
            className={cn(
              "rounded-md px-1 py-1",
              createBgColor(info.row.index),
            )}
          >
            {info.getValue()}
          </Label>
        ),
      }),
  }),
  columnHelper.accessor("Batch", {
    header: "批次",
    cell: (info) =>
      cellContainer({
        className: "mx-2 w-auto items-center-safe ",
        children: <Label>{info.getValue()}</Label>,
      }),
  }),
  columnHelper.accessor("Title", {
    header: () =>
      cellContainer({
        className: "w-full items-center justify-center",
        children: "标题",
      }),
    enableSorting: false,
    cell: (info) =>
      cellContainer({
        className: " items-center justify-center ",
        children: (
          <Label
            className={cn(
              "rounded-md px-1 py-1",
              createBgColor(info.row.index, 1),
            )}
            onClick={() => copyClipboard(info.getValue())}
          >
            {info.getValue()}
          </Label>
        ),
      }),
  }),
  columnHelper.accessor("SubTitle", {
    header: "副标题",
    enableSorting: false,
    cell: (info) =>
      cellContainer({
        className: "mx-2 w-auto items-center-safe ",
        children: <Label>{info.getValue()}</Label>,
      }),
  }),
  columnHelper.accessor("KeyPoint", {
    header: "要点摘要",
    enableSorting: false,
    cell: (info) =>
      cellContainer({
        className: "mx-2 w-auto items-center-safe ",
        children: <Label>{info.getValue()}</Label>,
      }),
  }),
  columnHelper.accessor("Content", {
    header: "内容",
    enableSorting: false,
    cell: (info) => (
      <Tooltip>
        <TooltipTrigger asChild>
          <div
            className="flex h-full w-full overflow-auto whitespace-pre"
            onDoubleClick={(e) => {
              const range = document.createRange();
              range.selectNodeContents(e.currentTarget);
              const selection = window.getSelection();
              selection?.removeAllRanges();
              selection?.addRange(range);
            }}
          >
            {info.getValue()}
          </div>
        </TooltipTrigger>
        <TooltipContent className="max-w-[600px] overflow-auto whitespace-pre">
          {info.getValue()}
        </TooltipContent>
      </Tooltip>
    ),
  }),
  columnHelper.accessor("Stats", {
    header: () =>
      cellContainer({
        className: "w-full items-center justify-center",
        children: "状态",
      }),
    cell: (info) =>
      cellContainer({
        className: "mx-2 items-center justify-center",
        children: (
          <Label
            className={cn(
              "rounded-md px-3 py-1",
              createBgColor(info.row.index, 2),
            )}
          >
            {info.getValue()}
          </Label>
        ),
      }),
  }),
  columnHelper.accessor("CreatTime", {
    header: "创建时间",
    cell: (info) =>
      cellContainer({
        className: "mx-2 w-auto items-center-safe ",
        children: <Label>{info.getValue()}</Label>,
      }),
  }),
] as ColumnDef<GenerateRowProps>[];

const copyClipboard = async (str: string) => {
  try {
    await navigator.clipboard.writeText(str);
    toast.success(`已复制: ${str}`, { position: "top-right" });
  } catch (error) {
    console.error("复制失败", error);
    toast.error("复制失败", { position: "top-right" });
  }
};

export { columns };
